/********************************************************************************
 * Project Name		[JavaEE_Web]
 * File Name     	[AclFilter.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package filter.acl.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import filter.HttpFilter;
import filter.acl.bean.Authority;
import filter.acl.bean.User;

/**
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
@WebFilter(filterName = "AclFilter", urlPatterns = "/jsp/acl/*")
public class AclFilter extends HttpFilter {

	@Override
	public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws IOException, ServletException {
		// 获取ServletPath
		String servletPath = request.getServletPath();

		// 不需要拦截的列表
		List<String> uncheckedList = Arrays.asList("/jsp/acl/login.jsp", "/jsp/acl/logout.jsp", "/jsp/acl/list.jsp",
				"/jsp/acl/authorityManage.jsp", "/jsp/acl/403.jsp");

		if (uncheckedList.contains(servletPath)) {
			filterChain.doFilter(request, response);
			return;
		} else {
			User user = (User) request.getSession().getAttribute("user");
			if (user == null) {
				// 如果用户未登陆
				response.sendRedirect(request.getContextPath() + "/jsp/acl/login.jsp");
			} else {
				// 如果用户已经登陆, 获得用户所有的权限
				List<Authority> authorities = user.getAuthorities();
				Authority authority = new Authority();
				authority.setUrl(servletPath);
				if (authorities.contains(authority)) { // contains方法依赖于equals()
					// 如果用户有权限, 直接访问
					filterChain.doFilter(request, response);
					return;
				} else {
					// 如果没有权限
					response.sendRedirect(request.getContextPath() + "/jsp/acl/403.jsp");
					return;
				}
			}
		}
	}
}
